/*
* user.js
* create time:2019-07-05 09:00
* author: LiJunYi
* */
layui.extend({
    dtree:'/static/layui_ext/dtree/dtree'
}).use(['dtree','layer','element','form','table'],function(){
    var layer = layui.layer // 弹层
        , table = layui.table //表格
        , form = layui.form
        ,dtree = layui.dtree
        , element = layui.element;

    /* 数据表格 */
    table.render({
        elem: '#userInfos'
        ,height: 400
        ,cellMinWidth:100
        ,url: '/user/list'
        ,where:{
            userName:'',
            departmentName:''
        }
        , title: '信息表'
        , even: true
        , defaultToolbar: []
        ,toolbar: '#toolbarDemo'
        , cols: [
            [
                {field: 'id', title: '用户标识',width:100,align: 'center',fixed: 'left'}
                , {field: 'userName', title: '登录名', align: 'center'}
                , {field: 'nickName', title: '昵称', align: 'center'}
                , {field: 'userSex', title: '性别', align: 'center'}
                , {field: 'userEmail', title: '邮箱',width:120, align: 'center'}
                , {field: 'userPhone', title: '手机号', align: 'center'}
                , {field: 'userImg', title: '头像', align: 'center',templet:'#userImgTp'}
                , {field: 'userType', title: '用户状态', align: 'center',templet: '#userTypeTP', unresize: true}
                , {field: 'departmentId', title: '部门', align: 'center',templet: '#depTp',event:'setDep'}
                ,{fixed: 'right', title:'操作', toolbar: '#barDemo', width:200}
            ]
        ]
        , page: true
        ,limits:[5,10,20,40,100]
        ,done:function () {
            // 表格图片hover事件 放大图片
            hoverOpenImg();
        }
    });
    //监听用户状态操作
    const user = {
        id:0,
        userType:1
    };
    form.on('switch(userType)', function(obj){
        user.id = this.value;
        if(false == obj.elem.checked){
            layer.confirm('确认要停用用户吗?', {
                btn: ['确定','取消'],icon:3,title:'系统提示'
            }, function(){
                stopOrStartUser(0);
            },function () {
                obj.elem.checked = true;
                form.render();
            });
        }else{
            layer.confirm('确认要启用用户吗?', {
                btn: ['确定','取消'],icon:3,title:'系统提示'
            }, function(){
                stopOrStartUser(1);
            },function () {
                obj.elem.checked = false;
                form.render();
            });
        }
    });
    /*停用启用用户方法*/
    function stopOrStartUser(userType){
        user.userType = userType;
        layer.closeAll();
        $.ajax({
            url:'/user/update_user_type',
            type:'post',
            data:user,
            success:function (obj) {
                if("权限不足" == obj.msg){
                    layer.msg(obj.msg,{icon:7,time:800});
                    form.render();
                }else{
                    layer.msg(obj,{icon:1,time:800});
                }
            }
        });
    }

    //头工具栏事件
    table.on('toolbar(user_operation)', function(obj){
        var checkStatus = table.checkStatus(obj.config.id);
        switch(obj.event){
            case 'dowmFile':
                layer.msg("模板下载");
                break;
            case 'getCheckFile':
                layer.msg("选择文件");
                break;
            case 'inserts':
                layer.msg("导入");
                break;
        };
    });

    //监听行工具事件
    table.on('tool(user_operation)', function(obj){
        var data = obj.data;
        //console.log(obj)
        if(obj.event === 'del'){
            layer.confirm('真的删除行么', function(index){
                obj.del();
                layer.close(index);
            });
        } else if(obj.event === 'edit'){
            layer.msg("重置");
        }else if(obj.event === 'role'){
            rolelicense(data.id);
        }else if(obj.event === 'setDep'){
            openDep(obj);
        }
    });

    //监听提交
    form.on('submit(formDemo)', function(data){
        table.reload('userInfos',{
            url:"/user/list",
            page:{
                curr:1
            },
            where:{
                userName:data.field.userName,
                departmentName:data.field.departmentName
            },
            page:true
        });
        return false;
    });

    /*解决表格行工具栏按钮过多展开失效start*/
    // 缓存当前操作的是哪个表格的哪个tr的哪个td
    $(document).off('mousedown','.layui-table-grid-down')
        .on('mousedown','.layui-table-grid-down',function(event){
            table._tableTrCurr = $(this).closest('td');
        });

    $(document).off('click','.layui-table-tips-main [lay-event]')
        .on('click','.layui-table-tips-main [lay-event]',function(event){
            var elem = $(this);
            var tableTrCurr = table._tableTrCurr;
            if(!tableTrCurr){
                return;
            }
            var layerIndex = elem.closest('.layui-table-tips').attr('times');
            // 关闭当前这个显示更多的tip
            layer.close(layerIndex);
            table._tableTrCurr.find('[lay-event="' + elem.attr('lay-event') + '"]').first().click();
        });
    /*解决表格行工具栏按钮过多展开失效end*/

    /*用户角色许可*/
    function rolelicense(uId){
        layer.open({
           type:2,
            title:"用户角色管理",
            content:"/user/role/"+uId,
            area:['500px','400px'],
            btn:['授权','关闭'],
            btnAlign: 'c',
            scrollbar: false,
            resize:false,
            anim: 3,
            shade: [0.8, '#393D49'],
            yes:function(index, layero){
                var body = layer.getChildFrame('body', index);
                body.find('form button:eq(0)').click();// 触发提交监听
                setTimeout(function () {
                    layer.close(index);
                },1500);
            },btn2:function(index, layero){
                layer.close(index);
            }
        });
    }
    /*监听授权表单提交*/
    form.on('submit(formUserRole)', function(data){
        $.ajax({
           url:"/user/assign",
            type:"post",
           data:data.field,
            success:function(obj){
                if("权限不足" == obj.msg){
                    layer.msg(obj.msg,{icon:7,time:800});
                }else if(1 == obj){
                    layer.msg("操作成功",{icon:1,time:800});
                }else{
                    layer.msg("操作失败",{icon:2,time:800});
                }
            },
            dataType:"json"
        });
        return false;
    });

    /** 用户修改部门*/
    function openDep(obj) {
        let data = obj.data;
        layer.open({
           type:1,
            title:'部门列表',
            area:['400px','80%'],
            content: '<ul id="openTree1" class="dtree" data-id="0"></ul>',
            btn:['确认','关闭'],
            success: function(layero, index){
                var DTree = dtree.render({
                    elem: "#openTree1",
                    url: "/dep/list",
                    dataFormat: "list", //配置data的风格为list
                    done:function () {
                        var params = dtree.dataInit("openTree1",data.departmentId);
                    }
                });
            },
            yes: function(index, layero) {
                layer.close(index);
                var param = dtree.getNowParam("openTree1"); // 获取当前选中节点
                console.log(param);
                let depId = param.nodeId;
                let id = data.id;
                $.ajax({
                   url:'/user/update_user_dep/'+id+'/'+depId,
                   type:'post',
                   dataType: 'json',
                   success:function (data) {
                       $(".layui-laypage-btn").click();
                      if("ok" == data.msg){
                          //同步更新表格和缓存对应的值
                          layer.alert("操作成功",{time:800});
                      }else{
                          layer.alert("操作失败",{time:800});
                      }
                   }
                });
            }
        });
    }
});
function hoverOpenImg(){//鼠标悬浮显示头像大图
    var img_show = null; // tips提示
    $('td img').hover(function(){
        var img = "<img class='img_msg' src='"+$(this).attr('src')+"' style='width:100%;' />";
        img_show = layer.tips(img, this,{
            tips:[2, 'rgba(41,41,41,.0)']
            ,area: ['12%']
        });
    },function(){
        layer.close(img_show);
    });
    $('td img').attr('style','max-width:70px');
}